
import UIKit

extension UITextField {
    
    /// 添加左侧视图
    /// - Parameters:
    ///   - width: 视图总宽度
    ///   - icon: <#icon description#>
    ///   - iconSize: <#iconSize description#>
    func addPadding(left width: CGFloat, icon: UIImage? = nil, iconSize: CGSize = .zero) {
        leftView = makeCustomView(width, icon: icon, iconSize: iconSize)
        leftViewMode = .always
    }
    
    /// 添加右侧视图
    /// - Parameters:
    ///   - width: 视图总宽度
    ///   - icon: <#icon description#>
    ///   - iconSize: <#iconSize description#>
    func addPadding(right width: CGFloat, icon: UIImage? = nil, iconSize: CGSize = .zero) {
        rightView = makeCustomView(width, icon: icon, iconSize: iconSize)
        rightViewMode = .always
    }
    
    //MARK: - view
    private func makeCustomView(_ width: CGFloat, icon: UIImage?, iconSize: CGSize) -> UIView {
        let appendView = UIView(frame: CGRect(origin: .zero, size: CGSize(width: width, height: self.frame.height)))
        if let iconImage = icon {
            let imageView = UIImageView(frame: CGRect(origin: CGPoint(x: appendView.frame.width/2 - iconSize.width/2, y: appendView.frame.height/2 - iconSize.height/2), size: iconSize))
            imageView.image = iconImage
            appendView.addSubview(imageView)
        }
        return appendView
    }
    
}

extension UITextField: RaeToolProtocol {
    
    private struct AssociatedKey {
        /// 字体
        static var fontKey                  = "textField_placeholder_font"
        /// 字体颜色
        static var placeholderColor         = "textField_placeholder_color"
        
        static let placeholderTag           = 984601
    }
    
    /// 文本字体
//    var placeholderFont: UIFont? {
//        get {
//            return objc_getAssociatedObject(self, &AssociatedKey.fontKey) as? UIFont ?? UIFont.systemFont(ofSize: 14)
//        } set {
//            objc_setAssociatedObject(self, &AssociatedKey.fontKey, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)
//            self.makeOrModifyPlaceholder()
//        }
//    }
    
    /// 文本颜色
//    var placeholderColor: UIColor? {
//        get {
//            return objc_getAssociatedObject(self, &AssociatedKey.placeholderColor) as? UIColor ?? UIColor.lightText
//        } set {
//            objc_setAssociatedObject(self, &AssociatedKey.placeholderColor, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)
//            self.makeOrModifyPlaceholder()
//        }
//    }
    
    func placehold(_ color: UIColor, font: UIFont?, icon: UIImage? = nil, iconSize: CGSize = .zero, imageInFirst: Bool = true) {
        guard let text = placeholder, !text.isEmpty else { return }
        let attri = rae.makeAttriString(text, font: font, color: color, image: icon, imageSize: iconSize, imageInFirst: imageInFirst)
        attributedPlaceholder = attri
    }
    
}
